package fina2.remove;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.seam.Component;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;
import org.jboss.seam.servlet.ContextualHttpServletRequest;

import fina2.dcs.common.DCSUIUtil;
import fina2.dcs.upload.UploadedFileLocal;
import fina2.upload.UploadBean;

@SuppressWarnings("serial")
public class RemoveServlet extends HttpServlet {

	private Log log = Logging.getLog(getClass());

	private UploadedFileLocal ufl = null;
	private UploadBean ub = null;

	private void wrappedGet(HttpServletRequest req, HttpServletResponse res) {
		ArrayList<Long> idsList = null;

		if (req.getParameter("id") == null) {
			return;
		}
		try {
			idsList = DCSUIUtil.parseString(req.getParameter("id"), ",");
			ufl = (UploadedFileLocal) Component.getInstance("uploadFileSession");
			ufl.removeFile(idsList);
			ub = (UploadBean) Component.getInstance("uploadBean");
			ufl.loadUploadedFiles(ub.getUploadedFile());
			res.sendRedirect("/fina-dcs-wp/security/data.seam");

		} catch (Exception ex) {
			try {
				res.sendRedirect("/fina-dcs-wp/security/removeError.html");
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
			log.error("Error during removing file " + ex.getMessage(), ex);
		} finally {
			if (idsList != null)
				idsList.clear();
		}

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		final HttpServletRequest req = request;
		final HttpServletResponse res = response;
		new ContextualHttpServletRequest(req) {
			public void process() throws Exception {
				wrappedGet(req, res);
			}
		}.run();

	}
}
